import time

from iot import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser
from TOOL.main import implant
from TOOL.analysis import analysis
from TOOL.OSS import put_object_oss
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
import uuid


class implant(APIView):

    def post(self, request):
        # 从请求中获取图片文件对象
        image_file = request.FILES['image']
        print(type(image_file))
        # 将处理后的图片保存在服务器上
        path = default_storage.save('images/' + image_file.name, ContentFile(image_file.read()))
        print(image_file.read())
        file_name = f"{uuid.uuid4()}_{image_file}"
        # 构造图片访问链接并返回
        image_url = put_object_oss(ObjectName=file_name, LocalFile=image_file.read())
        return Response({'image_url': image_url})


class analysis(APIView):
    def get(self, request):
        pass
        # try:
        #     publish.single(settings.MQTT_TOPIC, "off", hostname=settings.MQTT_HOSTNAME)
        #     return Response({'status': 200, 'msg': '关灯成功！'})
        # except Exception as e:
        #     return Response({'status': 201, 'msg': '关灯失败'})
